﻿using System;
using System.Data;
using System.Text;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using SYDZ.WMS.DBUtility;
using ElectronicWMSA.Comm.ClassFiles;
using ElectronicWMSA.Comm.Forms.Message;
using ElectronicWMSA.List.Second;

namespace ElectronicWMSA.Warehouse
{
    public partial class List_StockOutGoingReportFrm : Form
    {
        private string strWhere1 = "", strWhere2 = "";
        public List_StockOutGoingReportFrm()
        {
            InitializeComponent();
        }

        private void List_StockOutGoingReportFrm_Load(object sender, EventArgs e)
        {
            dtpTime1.Value = DateTime.Now.AddDays(-7);
            txt_15.SelectedIndex = 0;
            page1.PageCurrent = 1; page1.PageSize = 500;
            page2.PageCurrent = 1; page2.PageSize = 500;
        }
        DataTable dt1 = new DataTable();
        private int DBindData1()
        {
            Comm.Forms.MsControls.PageData pageData = new Comm.Forms.MsControls.PageData();
            try
            {
                pageData.TableName = "T_PickStockPrepare";
                pageData.PrimaryKey = "NID";
                pageData.OrderStr = "NID  DESC";
                pageData.PageIndex = page1.PageCurrent;
                pageData.PageSize = page1.PageSize;
                pageData.QueryCondition = strWhere1;
                pageData.QueryFieldName = "*";
                WaitingBoxFrm wf = new WaitingBoxFrm((obj, args) => { Thread.Sleep(500); pageData.QueryDataTable(); }, 500); wf.ShowDialog(this);
                page1.bindingSource.DataSource = pageData.dsInfo.Tables[0]; 
                page1.bindingNavigator.BindingSource = page1.bindingSource;
                dgv1.AutoGenerateColumns = false;
                dgv1.DataSource = page1.bindingSource;
                dgv1.ClearSelection();
                dgv1.CurrentCell = null;
                if (dgv1.RowCount > 0)
                {
                    string _Modelstr = "", _Numbestr = "";
                    for (int i = 0; i < dgv1.RowCount; i++)
                    {
                        if (_Modelstr == "")
                            _Modelstr = "'" + dgv1.Rows[i].Cells["Product_Model"].Value + "'";
                        else
                            _Modelstr += ",'" + dgv1.Rows[i].Cells["Product_Model"].Value + "'";
                        if (_Numbestr == "")
                            _Numbestr = "'" + dgv1.Rows[i].Cells["Serial_Number"].Value + "'";
                        else
                            _Numbestr += ",'" + dgv1.Rows[i].Cells["Serial_Number"].Value + "'";
                    }
                    string str = " 1=1 ";
                    if (_Modelstr != "") str += " AND Product_Model IN(" + _Modelstr + ") ";
                    if (_Numbestr != "") str += " AND Serial_Number IN(" + _Numbestr + ") ";
                    if (str != " 1=1 ")
                    {
                        dt1 = new DataTable();
                        dt1 = DbHelperSQL.Query("SELECT MIN(Update_Time) AS Update_Time,Product_Model,Serial_Number FROM T_Stock WHERE " + str + " GROUP BY Product_Model,Serial_Number").Tables[0];
                        if (dt1.Rows.Count > 0)
                        {
                            for (int i = 0; i < dgv1.RowCount; i++)
                            {
                                DataRow[] _DataRow = dt1.Select("Product_Model='" + dgv1.Rows[i].Cells["Product_Model"].Value + "' AND Serial_Number='" + dgv1.Rows[i].Cells["Serial_Number"].Value + "' ");
                                if (_DataRow.Length > 0)
                                {
                                    dgv1.Rows[i].Cells["RuKu_Time1"].Value = _DataRow[0][0].ToString();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLogLoad.ErrorLogInfo(ex.Message.ToString());
                MessageClass.error("数据异常？");
            }
            return pageData.TotalCount;
        }
        private int DBindData2()
        {
            Comm.Forms.MsControls.PageData pageData = new Comm.Forms.MsControls.PageData();
            try
            {
                pageData.TableName = "T_PickStockPrepare";
                pageData.PrimaryKey = "NID";
                pageData.OrderStr = "NID  DESC";
                pageData.PageIndex = page2.PageCurrent;
                pageData.PageSize = page2.PageSize;
                pageData.QueryCondition = strWhere2;
                pageData.QueryFieldName = "*";
                WaitingBoxFrm wf = new WaitingBoxFrm((obj, args) => { Thread.Sleep(500); pageData.QueryDataTable(); }, 500); wf.ShowDialog(this);
                page2.bindingSource.DataSource = pageData.dsInfo.Tables[0];
                page2.bindingNavigator.BindingSource = page2.bindingSource;
                dgv2.AutoGenerateColumns = false;
                dgv2.DataSource = page2.bindingSource;
                dgv2.ClearSelection();
                dgv2.CurrentCell = null;
                string _Modelstr = "", _Numbestr = "";
                for (int i = 0; i < dgv2.RowCount; i++)
                {
                    if (_Modelstr == "")
                        _Modelstr = "'" + dgv2.Rows[i].Cells["Product_Model2"].Value + "'";
                    else
                        _Modelstr += ",'" + dgv2.Rows[i].Cells["Product_Model2"].Value + "'";

                    if (_Numbestr == "")
                        _Numbestr = "'" + dgv2.Rows[i].Cells["Serial_Number2"].Value + "'";
                    else
                        _Numbestr += ",'" + dgv2.Rows[i].Cells["Serial_Number2"].Value + "'";
                }
                string str = " 1=1 ";
                if (_Modelstr != "") str += " AND Product_Model IN(" + _Modelstr + ") ";
                if (_Numbestr != "") str += " AND Serial_Number IN(" + _Numbestr + ") ";
                if (str != " 1=1 ")
                {
                    dt1 = new DataTable();
                    dt1 = DbHelperSQL.Query("SELECT MIN(Update_Time) AS Update_Time,Product_Model,Serial_Number FROM T_Stock WHERE " + str + " GROUP BY Product_Model,Serial_Number").Tables[0];
                    if (dt1.Rows.Count > 0)
                    {
                        for (int i = 0; i < dgv2.RowCount; i++)
                        {
                            DataRow[] _DataRow = dt1.Select("Product_Model='" + dgv2.Rows[i].Cells["Product_Model2"].Value + "' AND Serial_Number='" + dgv2.Rows[i].Cells["Serial_Number2"].Value + "' ");
                            if (_DataRow.Length > 0)
                            {
                                dgv2.Rows[i].Cells["RuKu_Time2"].Value = _DataRow[0][0].ToString();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLogLoad.ErrorLogInfo(ex.Message.ToString());
                MessageClass.error("数据异常？");
            }
            return pageData.TotalCount;
        }
        private int page1_EventPaging(Comm.Forms.MsControls.EventPagingArg e)
        {
            return DBindData1();
        }
        private int page2_EventPaging(Comm.Forms.MsControls.EventPagingArg e)
        {
            return DBindData2();
        }
        private void dgv1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            SolidBrush b = new SolidBrush(dgv1.RowHeadersDefaultCellStyle.ForeColor);
            e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), dgv1.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
        }

        private void dgv2_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            SolidBrush b = new SolidBrush(dgv2.RowHeadersDefaultCellStyle.ForeColor);
            e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), dgv2.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
        }

        private void btnUserSearch1_Click(object sender, EventArgs e)
        {
            strWhere1 = " 1=1 AND SUBSTRING(Serial_Number,16, 1) <> '_' ";
            if (!string.IsNullOrEmpty(txt_01.Text))
                strWhere1 += "  AND  OutList_NO LIKE '%" + txt_01.Text.Trim() + "%'";

            if (txt_02.Text.Trim() != "--请选择--" && txt_02.Text.Trim() != "")
                strWhere1 += " AND PickList_NO LIKE '%" + txt_02.Text.Trim() + "%' ";

            if (txt_03.Text.Trim() != "--请选择--" && txt_03.Text.Trim() != "")
                strWhere1 += " AND Replace(Product_Model,' ','')  LIKE  '%" + txt_03.Text.Trim() + "' ";

            if (!string.IsNullOrEmpty(txt_04.Text))
                strWhere1 += "  AND  Serial_Number LIKE '%" + txt_04.Text.Trim() + "%'";
            string _type = txt_05.Text.Trim();
            if (_type != "")
            {
                strWhere1 += "  AND  BK07 = '" + _type + "'";
                if (_type == "UPS")
                {
                    if (Ck_UPS4.Checked)//ups4
                        strWhere1 += " AND len(OutList_NO)>14  ";
                    else
                        strWhere1 += " AND len(OutList_NO)=14  ";
                }
                else if (_type == "基板")
                {

                }
            }

            if (cbk01.Checked)
            {
                if (dtpTime1.Checked)
                    strWhere1 += "  AND  convert(nvarchar(20),Update_Time,120)>= '" + dtpTime1.Text.Trim() + "'";
                if (dtpTime2.Checked)
                    strWhere1 += "  AND  convert(nvarchar(20),Update_Time,120) <= '" + dtpTime2.Text.Trim() + "'";
            }
            else
            {
                if (dtpTime1.Checked)
                    strWhere1 += "  AND  BK08 >= '" + dtpTime1.Text.Trim() + "'";
                if (dtpTime2.Checked)
                    strWhere1 += "  AND  BK08 <= '" + dtpTime2.Text.Trim() + "'";
            }

            page1.Bind();
        }

        private void btnUserSearch2_Click(object sender, EventArgs e)
        {
            strWhere2 = " 1=1 AND LEN(Serial_Number) > 15 AND SUBSTRING(Serial_Number,16, 1) = '_' ";
            if (!string.IsNullOrEmpty(txt_11.Text))
                strWhere2 += "  AND  OutList_NO LIKE '%" + txt_11.Text.Trim() + "%'";
            if (txt_12.Text.Trim() != "--请选择--" && txt_12.Text.Trim() != "")
                strWhere2 += "  AND PickList_NO LIKE '%" + txt_12.Text.Trim() + "%' ";
            if (txt_13.Text.Trim() != "--请选择--" && txt_13.Text.Trim() != "")
                strWhere2 += "  AND Replace(Product_Model,' ','')  LIKE  '%" + txt_13.Text.Trim() + "' ";
            if (!string.IsNullOrEmpty(txt_14.Text))
                strWhere2 += "  AND  Serial_Number LIKE '%" + txt_14.Text.Trim() + "%'";
            if (cbk02.Checked)
            {
                if (dtpTime3.Checked)
                    strWhere2 += "  AND  convert(nvarchar(20),Update_Time,120)>= '" + dtpTime3.Text.Trim() + "'";
                if (dtpTime4.Checked)
                    strWhere2 += "  AND  convert(nvarchar(20),Update_Time,120) <= '" + dtpTime4.Text.Trim() + "'";
            }
            else
            {
                if (dtpTime3.Checked)
                    strWhere2 += "  AND  BK08 >= '" + dtpTime3.Text.Trim() + "'";
                if (dtpTime2.Checked)
                    strWhere2 += "  AND  BK08 <= '" + dtpTime4.Text.Trim() + "'";
            }
            page2.Bind();
        }
        /// <summary>
        /// 扫描时间导出
        /// </summary>
        private void btnExport1_Click(object sender, EventArgs e)
        {
            string SelectSQL = " select  [OutList_NO] as 'PO',[PickList_NO] as'装箱单',BK10 as '仕向地',[Product_Model] as '机型',[Serial_Number] as '序列号',BK08 as'出库日期',[BanHao] as '板号'  from [T_PickStockPrepare]   ";
            if (strWhere1 != "")
            {
                SelectSQL += " WHERE " + strWhere1 + " ORDER BY Update_Time ASC  ";
            }
            DataTable dt = DbHelperSQL.ExecuteDataTable(SelectSQL);
            if (dt.Rows.Count > 0)
            {
                ExPut.GetNopiExcel(dt);
            }
            else
            {
                MessageClass.error("无数据，请确认！");
            }
        }

        private void btnExport2_Click(object sender, EventArgs e)
        {
            string SelectSQL = " select  [OutList_NO] as 'PO',[PickList_NO] as'装箱单',BK10 as '仕向地',[Product_Model] as '机型',[Serial_Number] as '序列号',BK08 as'出库日期',[BanHao] as '板号'  from [T_PickStockPrepare]   ";
            if (strWhere1 != "")
            {
                SelectSQL += " WHERE " + strWhere2 + " ORDER BY Update_Time ASC  ";
            }
            DataTable dt = DbHelperSQL.ExecuteDataTable(SelectSQL);
            if (dt.Rows.Count > 0)
            {
                ExPut.GetNopiExcel(dt);
            }
            else
            {
                MessageClass.error("无数据，请确认！");
            }
        }
        /// <summary>
        /// 导出UPS 3个
        /// </summary>
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {

                DataTable dt = new DataTable();
                string SelectSQL = " select  [PickList_NO] as'装箱单',[Product_Model] as '机型',[Serial_Number] as '序列号' from [T_Stock]   ";
                if (strWhere1 != "")
                {
                    SelectSQL += " where " + strWhere1 + "   order by left(PickList_NO,10),Create_Time  ASC   ";
                }
                dt = DbHelperSQL.ExecuteDataTable(SelectSQL);

                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "txt(*.txt)|*.txt";
                saveFileDialog1.FilterIndex = 0;
                saveFileDialog1.RestoreDirectory = true;
                saveFileDialog1.CreatePrompt = true;
                saveFileDialog1.Title = "导出txt文件到 ";
                saveFileDialog1.ShowDialog();

                string sSaveFullPath = saveFileDialog1.FileName;//导出全路径
                string path = sSaveFullPath;
                StringBuilder builder = new StringBuilder();
                foreach (DataRow dr in dt.Rows)
                {
                    builder.AppendLine(dr[0].ToString() + ',' + dr[1].ToString().PadRight(12, ' ') + ',' + dr[2].ToString().PadRight(12, ' '));
                    using (System.IO.FileStream file = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        using (System.IO.TextWriter text = new System.IO.StreamWriter(file, System.Text.Encoding.Default))
                        {
                            text.Write(builder.ToString());
                        }
                    }
                }

            }
            catch (Exception)
            {

            }
        }

        /// <summary>
        /// 导出UPS 4个
        /// </summary>
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = new DataTable();
                string SelectSQL = " select  [PickList_NO] as'装箱单',[Product_Model] as '机型',[Serial_Number] as '序列号' , OutList_NO  from [T_Stock]   ";
                if (strWhere1 != "")
                {
                    SelectSQL += " where " + strWhere1 + "  order by left(PickList_NO,10),Create_Time   asc   ";
                }
                dt = DbHelperSQL.ExecuteDataTable(SelectSQL);
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "txt(*.txt)|*.txt";
                saveFileDialog1.FilterIndex = 0;
                saveFileDialog1.RestoreDirectory = true;
                saveFileDialog1.CreatePrompt = true;
                saveFileDialog1.Title = "导出txt文件到 ";

                saveFileDialog1.ShowDialog();

                string sSaveFullPath = saveFileDialog1.FileName;//导出全路径
                string path = sSaveFullPath;
                StringBuilder builder = new StringBuilder();
                foreach (DataRow dr in dt.Rows)
                {

                    builder.AppendLine(dr[0].ToString() + ',' + dr[1].ToString().PadRight(12, ' ') + ',' + dr[2].ToString().PadRight(12, ' ') + ',' + dr[3].ToString());
                    using (System.IO.FileStream file = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        using (System.IO.TextWriter text = new System.IO.StreamWriter(file, System.Text.Encoding.Default))
                        {
                            text.Write(builder.ToString());
                        }
                    }
                }

            }
            catch (Exception)
            {

            }
        }

        private void btnPageData1_Click(object sender, EventArgs e)
        {
            if (dgv1.Rows.Count > 0)
            {
                ExcelUtil.ExportDataGridViewToExcel(dgv1);
            }
            else
            {
                MessageClass.error("无数据，请确认！");
            }
        }
        private void btnPageData2_Click(object sender, EventArgs e)
        {
            if (dgv2.Rows.Count > 0)
            {
                ExcelUtil.ExportDataGridViewToExcel(dgv2);
            }
            else
            {
                MessageClass.error("无数据，请确认！");
            }
        }
        #region  Close
        private void linkLabelClose_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseTabPages();
        }

        private void linkLabellinkLabelCloseAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseAllTabPages();
        }

        private void btnImput_Click(object sender, EventArgs e)
        {
            ImportWindos frm = new ImportWindos();
            frm.ShowDialog();
        }

        private void dtpTime1_ValueChanged(object sender, EventArgs e)
        {

        }

        private void linkLabelCloseElse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseTabPageElse();
        }
        #endregion

    }
}
